<template>
  <sv-page :showNavBar="false">
    <sv-nav-bar :pageTitle="pageTitle"></sv-nav-bar>
    <view class="lib-detail">
      <view class="padding-top" v-if="libData?.banner.length > 0">
        <uv-swiper
          :list="libData.banner"
          autoplay
          circular
          showTitle
          keyName="url"
          :title-style="{ color: 'red', textAlign: 'center' }"
          previousMargin="30"
          nextMargin="30"
          radius="5"
          bgColor="transparent"
        ></uv-swiper>
      </view>
      <!-- 题库信息 -->
      <uv-skeletons :loading="loading" :skeleton="skeletonHeader">
        <view class="cu-bar padding-top">
          <view class="action text-blue">
            <text class="cuIcon-titles"></text>
            <text class="text-bold">{{ libData?.lib_name }}</text>
            <view class="text-olive margin-left-sm flex-vc" v-if="needVip">
              <view class="sv-icons-vip"></view>
              <view class="text-sm margin-left-xs">会员专享</view>
            </view>
          </view>
        </view>
        <view class="padding-lr margin-top-sm">
          <view class="line-height-2 flex">
            <text class="text-cyan flex-shrink-0">标题</text>
            <text class="margin-left-sm">
              {{ libData?.lib_title }}
            </text>
          </view>
          <view class="line-height-2 flex">
            <text class="text-cyan flex-shrink-0">简介</text>
            <text class="margin-left-sm">
              {{ libData?.intro }}
            </text>
          </view>
          <view class="line-height-2 flex">
            <text class="text-cyan flex-shrink-0">范围</text>
            <text class="margin-left-sm">
              {{ libData?.befit }}
            </text>
          </view>
          <view class="line-height-2 flex">
            <text class="text-cyan flex-shrink-0">来源</text>
            <text class="margin-left-sm">
              {{ libData?.origin }}
            </text>
          </view>
          <view class="line-height-2 text-right text-sm">
            <text class="cuIcon-pay text-df text-green padding-right-xs"></text>
            <text class="text-green text-lg text-bold">{{ libData?.sell_num || '--' }}</text>
            人已购买
            <text
              class="text-df text-red margin-left padding-right-xs"
              :class="[isFav ? 'cuIcon-likefill' : 'cuIcon-like']"
            ></text>
            <text class="text-red text-lg text-bold">{{ libData?.fav_num || '--' }}</text>
            人已收藏
          </view>
        </view>

        <!-- 单元章节 -->
        <view class="cu-bar margin-bottom-xs">
          <view class="action text-blue">
            <text class="cuIcon-titles"></text>
            <text class="text-bold">章节目录</text>
          </view>
        </view>
        <view class="padding-lr sv-uv-collapse">
          <uv-collapse :border="false">
            <uv-collapse-item
              v-for="item in libData?.lib_chapter"
              :key="item.key"
              :title="item.value"
              :name="item.key"
              :border="false"
            >
              <text>{{ item?.content }}</text>
            </uv-collapse-item>
          </uv-collapse>
        </view>
      </uv-skeletons>
      <!-- 底部占位 -->
      <view class="tabbar-placehoder margin-top"></view>
      <!-- 底部栏 -->
      <view class="pay-footer cu-bar tabbar border shop foot">
        <view class="action" style="width: 40%">
          <text class="text-price text-orange text-xxl text-bold">
            {{ convertFenToYuan(libData?.price - libData?.discount) }}
          </text>
          <text class="margin-left-sm margin-right-xs text-red">原价</text>
          <text class="text-price text-red text-lg text-delete-line">
            {{ convertFenToYuan(libData?.price) }}
          </text>
        </view>
        <view class="btn-group">
          <button
            class="cu-btn round shadow-blur"
            :class="[isFav ? 'bg-gradual-red' : 'bg-gradual-blue']"
            :disabled="loading"
            @click="onFav"
          >
            {{ isFav ? '取消收藏' : '添加收藏' }}
          </button>
          <button
            class="cu-btn bg-gradual-green round shadow-blur"
            :disabled="loading"
            @click="onStart"
          >
            {{ isBuy ? '开始练习' : '立即购买' }}
          </button>
        </view>
      </view>
    </view>
  </sv-page>
</template>

<script setup>
import { onLoad } from '@dcloudio/uni-app'
import { computed, ref } from 'vue'
import { libList } from '@/service/api/lib.js'
import { buyLibAdd, buyLibList, favLibAdd, favLibDelete, favLibList } from '@/service/api/record'
import { store } from '@/uni_modules/sv-id-pages/common/store'
import { judgeLogin, useThrottle } from '@/utils/util.js'
import { useSysStore } from '../../store/sys'
import { convertFenToYuan } from '@/uni_modules/sv-exam-plus/utils'
import { vipVerify } from '@/service/api/vip'

const options = ref()
const pageTitle = computed(() => {
  return options.value?.lib_name || '题库详情'
})
const libData = ref()

onLoad(async (option) => {
  options.value = option

  uni.showLoading({
    title: '加载中...',
    mask: true
  })
  await getVipVerify()
  await getLib()
  await handleInit()
  uni.hideLoading()
})

const skeletonHeader = [
  {
    type: 'flex',
    num: 1,
    style: 'padding:30rpx',
    children: [
      {
        type: 'line',
        num: 5,
        gap: '30rpx',
        style: ['width:30%', 'width:70%', 'width:80%', 'width:60%', 'width:90%']
      }
    ]
  },
  {
    type: 'flex',
    num: 1,
    style: 'padding:30rpx',
    children: [
      {
        type: 'line',
        num: 5,
        gap: '30rpx',
        style: ['width:30%', 'width:70%', 'width:80%', 'width:60%', 'width:90%']
      }
    ]
  }
]

const loading = ref(true)
const isFav = ref(false)
const isBuy = ref(false)
const isVip = ref(false)
const needVip = ref(false)

async function getVipVerify() {
  if (store.hasLogin) {
    const verifyRes = await vipVerify({ user_id: store.userInfo._id })
    isVip.value = verifyRes.data?.vip
  }
}

async function handleInit() {
  if (store.hasLogin) {
    const favLibRes = await favLibList({ user_id: store.userInfo._id })
    isFav.value = favLibRes.data?.some((item) => item.lib_id == libData.value.lib_id)

    const buyLibRes = await buyLibList({ user_id: store.userInfo._id })
    isBuy.value = buyLibRes.data?.some((item) => item.lib_id == libData.value.lib_id)
  }
  loading.value = false
}

async function getLib() {
  if (!options.value?.lib_id) return

  const libRes = await libList({
    lib_id: options.value.lib_id
  })
  libData.value = libRes.data[0]
  needVip.value = libData.value?.vip ? true : false
  // console.log('==== libData :', libData.value)
}

function onFav() {
  // 节流操作
  if (!useThrottle()()) return
  // 判断登录
  const isLogin = judgeLogin()
  // 未登录不予收藏
  if (!isLogin) return

  isFav.value = !isFav.value
  if (isFav.value) {
    // 添加收藏
    favLibAdd({
      user_id: store.userInfo._id,
      lib_id: libData.value.lib_id
    })
    libData.value.fav_num += 1 // 无感更新
  } else {
    // 取消收藏
    favLibDelete({
      user_id: store.userInfo._id,
      lib_id: libData.value.lib_id
    })
    libData.value.fav_num -= 1 // 无感更新
  }
}

// 开始练习/立即购买
function onStart() {
  // 判断登录
  const isLogin = judgeLogin()
  // 未登录不予开始
  if (!isLogin) return

  // 如果题库是VIP专享题库且当前用户不是VIP
  if (needVip.value && !isVip.value) {
    uni.showModal({
      title: '系统提示',
      content: '该题库为VIP专享题库哦',
      showCancel: true,
      confirmText: '获取VIP',
      success: ({ confirm }) => {
        if (confirm) {
          uni.navigateTo({ url: '/uni_modules/sv-id-vip/pages/vip/vip' })
        }
      }
    })
    return
  }

  if (isBuy.value) {
    // 开始答题 - 注意tabbar页面路径后不能带参数
    // 这里需要将题库数据通过pinia持久化缓存
    uni.switchTab({
      url: '/pages/home/home'
    })
    const { lib_id, lib_name, lib_chapter, unit_index = 0 } = libData.value
    useSysStore().setConfig({
      curTabIndex: 2,
      curLib: { lib_id, lib_name, lib_chapter, unit_index }
    })
  } else {
    uni.showModal({
      title: '购买提示',
      content: `是否购买${libData.value?.lib_name}`,
      showCancel: true,
      success: async ({ confirm }) => {
        if (confirm) {
          // 支付操作 或者折扣大于定价时直接添加入库，不再进行支付操作
          if (libData.value.price <= libData.value.discount) {
          }
          await buyLibAdd({
            user_id: store.userInfo._id,
            lib_id: libData.value.lib_id
          })
          isBuy.value = true
        }
      }
    })
  }
}
</script>

<style lang="scss">
.lib-detail {
  min-height: var(--page-main-height);

  .pay-footer {
    z-index: 99999;
    @include useTheme {
      background-color: #{getTheme('sv-card-color')};
    }
  }
}
</style>
